import Api from '../../api/Api';
import util from '../util/util';
import '../../asset/plugin/jquery-form/jquery.form.min';

import ImgTpl from './tpl/img.html';
import FileTpl from './tpl/file.html';
import UploadTpl from './upload.html';
import './upload.scss';
/**
 * 
 * @param {*} options 
 * options {
 *      itemsWrap: 展示上传文件的dom
 *      hasFile: 是否包含文件 默认false
 *      onlyFile: 只包含文件 默认false
 *      callback: 上传成功回调，传入此参数需要自己处理返回数据
 *      memory: 数据存储
 *      maxNumber: 最大数量
 * } 
 */
export default function upload(wrap, options) {
    let $itemsWrap, hasFile, maxNumber, callback, changeOption,
        onlyFile, reg, selectFile, title, type, $memory, url;

    setOptions(options, true);

    let isUpload = false;

    $(wrap).append(UploadTpl({title: title, selectFile: selectFile}))
    .on("change", "#js-upload-file-ipt", function() {
        const $form = $("#js-upload-form"), $text = $("#js-text-upload"),
            $this = $(this),  val = $this.val(), _this = this,
            files = _this.files, len = $itemsWrap.find('upload-item').length,
            num = 2,
            maxSize = num * 1024 * 1024;

        if(isUpload) {
            util.alertMessage('上传中，请稍后...');            
            return;
        }
        if(!val) {
            util.alertMessage('请添加上传的' + type + '！');
            return;
        }

        if(!reg.test(val)) {
            util.alertMessage('请上传正确的格式!');
            $form.get(0).reset();
            return;
        }
        if(files) {           
            for(let i = 0, l = files.length; i < l; i ++) {
                if(files[i].size > maxSize && /.*(\.jpg|png|gif|jpeg)$/i.test(val)) {
                    util.alertMessage('选择图片大小不能超过' + num + 'M！');
                    return;
                }
            }
        };
        isUpload = true;
        $text.text('上传中...');
        $form.ajaxSubmit({
            url: url || Api.uploadAttach,
            type: 'post',
            success: function(json) {
                json = JSON.parse(json)
                if(json.data) {
                    const result = json; 
                    if(typeof callback === 'function') {
                        callback(result);
                    }else {
                        const obj = {
                            name: result.data,
                            url: result.data
                        }
                        $memory.val(result.data);
                        $itemsWrap.html(options.type == 'file' ? FileTpl(obj) : ImgTpl(obj));
                        bindEvent();             
                    }
                }else {
                    util.alertMessage(json.error)
                }
            },
            error: function() {
                util.alertMessage('上传失败，请重试！');
            },
            complete: function() {
                isUpload = false;
                if(maxNumber == 1) {
                    close();
                }
                $text.text(selectFile);
                $form.get(0).reset();                
            }
        })
    })
    .on("click", "#js-upload-close", function() {
        close()
    });

    function bindEvent() {
        $('.js-del-upload').off('click').on("click", function() {
            let memorySelector = $(this).data('memory'),
                $standbyMemory = $(memorySelector);
            //    memoryArr = JSON.parse($memory.length ? $memory.val() : $standbyMemory.val()), url = $(this).attr("data-url");
            //
            //for(let i = 0, l = memoryArr.length; i < l; i ++) {
            //    if(memoryArr[i].data == url) {
            //        memoryArr.splice(i, 1);
            //        break;
            //    }
            //}
            ($memory.length ? $memory : $standbyMemory).val('');
            $(this).parents('.upload-item').remove();
        })
    }
    function close() {
        $("#js-upload-outer-wrap").hide(100);
    }

    function open() {
        const memory = $memory.val() || '';
        $("#js-upload-outer-wrap").show(100);
    }

    function setOptions(options = {}, init) {
        $itemsWrap = $(options.itemsWrap), 
        $memory = $(options.memory), 
        hasFile = options.hasFile, 
        maxNumber = options.maxNumber,
        callback = options.callback,
        url = options.url,
        changeOption = options.changeOptions,
        onlyFile = options.onlyFile,
        reg = onlyFile ? /.*(\.word|excel|pdf|xlsx)$/i : (hasFile ? /.*(\.jpg|png|gif|jpeg|word|excel|pdf|xlsx)$/i : /.*(\.jpg|png|gif|jpeg)$/i),
        selectFile = hasFile || onlyFile ? '选择文件' : '选择图片',
        title = hasFile || onlyFile ? '上传文件' : '上传图片',
        type = hasFile || onlyFile ? '文件' : '图片';
        if(!init && $itemsWrap.length == 0 && typeof callback !== 'function') {
            console.error('参数错误');
            return;
        }
        $itemsWrap.addClass('img-item'); 
        $("#js-upload-outer-wrap").find('.title-text').text(title);
        $("#js-text-upload").text(selectFile);
        bindEvent();
    }
    const getBack = {
        open: function() {
            open();
            return this;
        },
        setOptions: function(options) {
            setOptions(options);
            return this;
        }
    }
    return getBack;
}